<template>
  <div class="form-fragment">
    <div class="form-container">
      <tbc-dynamic-form :form="dynamicForm" class="compact">
        <template v-slot:cat_name="scope">
          <el-input placeholder="商品分类" readonly v-model="scope.item.value">
            <template v-slot:append>
              <el-button icon="el-icon-search">切换分类</el-button>
            </template>
          </el-input>
          <el-tag size="medium" v-for="(item, index) in extCategories" :key="index" closable
                  @close="onExtCatDelete(index)"
                  style="margin-right: 10px" type="primary" effect="plain">{{ item.cat_name }}
          </el-tag>
          <el-button size="mini" @click="$refs.cat.show()" icon="el-icon-circle-plus-outline">添加分类</el-button>
        </template>

        <template v-slot:brand_name="scope">
          <div @click="$refs.brand.show()">
            <el-input placeholder="品牌" readonly v-model="scope.item.value" clearable
                      @clear="onBrandSelected({brand_id: '', brand_name: ''})">
              <template v-slot:append>
                <el-button icon="el-icon-search">选择</el-button>
              </template>
            </el-input>
          </div>
        </template>
      </tbc-dynamic-form>
    </div>
  </div>


  <goods-brand-selector ref="brand" @choice="onBrandSelected"/>
  <goods-cat-selector ref="cat" @select="onExtCatSelect"/>
</template>
<script lang="ts">
import {defineComponent, defineAsyncComponent, reactive, ref} from 'vue'
import {UnwrapNestedRefs} from '@vue/reactivity'

interface Category {
  cat_id: string,
  cat_name: string
}

export default defineComponent({

  components: {
    GoodsBrandSelector: defineAsyncComponent(() =>
        import('../GoodsBrandSelector.vue')),
    GoodsCatSelector: defineAsyncComponent(() =>
        import('../GoodsCatSelector.vue')),
  },

  setup() {
    const extCategories = ref<{ cat_id: string, cat_name: string }[]>([])
    const dynamicForm: UnwrapNestedRefs<any> = reactive([
      {label: '商品主分类', type: 'hidden', field: 'cat_id', value: '', remark: ''},
      {label: '商品分类', type: 'input', field: 'cat_name', value: '', remark: ''},
      {label: '商品名称', type: 'input', field: 'goods_name', value: '', remark: '(3 ~ 50个字符)'},
      {label: '简短名称', type: 'input', field: 'goods_short_name', value: ''},
      {
        label: '资源文件',
        type: 'file',
        field: 'file_url',
        value: '',
      },
      {
        label: '排序', type: 'input-number', field: 'sort_weight', value: 50, remark: '(值越大越靠前)',
      },
      {
        label: '有效期/天',
        type: 'input-number',
        field: 'effective_day',
        value: 0, remark: '(0表示不限制)',
      },
      {
        label: '销售状态', type: 'radio', field: 'sale_status', value: 1, options: [
          {label: '出售', value: 1},
          {label: '下架', value: 2},
        ],
      },
    ])

    const init = (data: Record<string, string | number>) => {
      initDynamicFormData(data)
    }

    // 初始化表单数据
    const initDynamicFormData = (data: { [k: string]: string | number | Category[]}) => {
      const catPath: string[] = [];
      if (data.cat_path) {
        (data.cat_path as Category[]).forEach((item: Category) => catPath.push(item.cat_name))
        data.cat_name = catPath.join(" > ")
      }
      dynamicForm.forEach((item: Record<string, any>) => {
        if (typeof data[item.field] !== 'undefined') item.value = data[item.field]
      })
    }


    const onBrandSelected = (data: { [k: string]: string }) => {
      dynamicForm.forEach((item: { [k: string]: string }) => {
        if (item.field === 'brand_name') item.value = data.brand_name
        if (item.field === 'brand_id') item.value = data.brand_id
      })
    }


    const onExtCatSelect = (data: string[], value: string[], label: string[]) => {
      extCategories.value.push({
        cat_id: value.pop() as string,
        cat_name: label.join(' / ')
      })
    }

    const onExtCatDelete = (index: number) => {
      extCategories.value.splice(index, 1)
    }

    const getFormData = (): Record<string, string | number> => {
      let form: Record<string, string | number> = {goods_type: 1}
      dynamicForm.forEach((item: Record<string, string | number>) => form[item.field] = item.value)
      return form
    }

    return {
      init,
      dynamicForm,
      onExtCatSelect,
      onExtCatDelete,
      onBrandSelected,
      extCategories,
      getFormData
    }
  }
})
</script>